import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/ChatMsg.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/GlobalEvent.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/comm_utils.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_lifecycle_state/flutter_lifecycle_state.dart';

class ChatPage extends StatefulWidget {
  @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends StateWithLifecycle<ChatPage> {
  EasyRefreshController controller = EasyRefreshController();
  int childCount = 0;
  var _item = [];

  @override
  void initState() {
    super.initState();
    _onMsgEvent();
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh.custom(
      enableControlFinishRefresh: true,
      header: CommWidget.commHeader(),
      emptyWidget: childCount == 0 ? CommWidget.nullWidget() : null,
      controller: controller,
      slivers: <Widget>[
        SliverList(
            delegate: SliverChildBuilderDelegate((context, index) {
          return _itemWidget(context, index);
        }, childCount: childCount))
      ],
      onRefresh: () => _getMsgList(),
    );
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  void onResume() {
    super.onResume();
    _getMsgList();
  }

  Widget _itemWidget(BuildContext context, int index) {
    ChatMsg msg = _item[index];
    Widget _headWidget = Container(
      width: 36,
      height: 36,
      margin: EdgeInsets.only(left: 10),
      child: ClipOval(
          child: CachedNetworkImage(
        imageUrl: Api.getUrl(msg.fromImage),
        fit: BoxFit.cover,
        errorWidget: (context, url, error) =>
            Image.asset(Comm.IMG_DEFAULT, fit: BoxFit.cover),
      )),
    );
    Widget _nameWidget = Container(
      margin: EdgeInsets.only(left: 54, top: 8),
      child: Text(
        msg.fromName,
        style: TextStyle(fontSize: 16),
      ),
    );
    Widget _timeWidget = Container(
      margin: EdgeInsets.only(top: 8, right: 10),
      child: Text(
        '${CommUtil.getTimeDiff("${msg.createAt}")}',
        style: TextStyle(color: Color(0xffBBBBBB), fontSize: 12),
      ),
    );
    Widget _contentWidget = Container(
      margin: EdgeInsets.only(bottom: 8, left: 54),
      constraints: BoxConstraints(maxWidth: Comm.screenWidth - 56),
      child: Text(
        msg.message,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(color: Color(0xffBBBBBB), fontSize: 12),
      ),
    );
    Widget _unReadWidget = Offstage(
      offstage: null == msg.unReadNum || msg.unReadNum == 0,
      child: Container(
        width: 22,
        height: 16,
        alignment: Alignment.center,
        margin: EdgeInsets.only(bottom: 8, right: 10),
        decoration: BoxDecoration(
            color: Colors.red, borderRadius: BorderRadius.circular(12)),
        child: Text(
          "${msg.unReadNum}",
          maxLines: 1,
          style: TextStyle(color: Colors.white, fontSize: 10),
        ),
      ),
    );
    return GestureDetector(
      child: Container(
        height: 56,
        width: MediaQuery.of(context).size.width,
        child: Stack(children: <Widget>[
          Align(alignment: Alignment.centerLeft, child: _headWidget),
          Align(alignment: Alignment.topLeft, child: _nameWidget),
          Align(alignment: Alignment.topRight, child: _timeWidget),
          Align(alignment: Alignment.bottomLeft, child: _contentWidget),
          Align(alignment: Alignment.bottomRight, child: _unReadWidget),
        ]),
      ),
      onTap: () {
        User user = new User();
        user.userId = msg.fromId;
        user.userName = msg.fromName;
        user.imgUrl = msg.fromImage;
        var jsons = jsonEncode(Utf8Encoder().convert(json.encode(user)));
        String url = '${Routers.PAGE_CHAT}?user=$jsons&msgTag=${msg.msgTag}';
        Routers.router
            .navigateTo(context, url, transition: TransitionType.inFromRight);
      },
    );
  }

  ///获取消息列表
  Future _getMsgList() async {
    Http.get("${Api.URL_CHAT_OFFLINE}", successCallBack: (data) {
      List list = json.decode(data).map((m) => ChatMsg.fromJson(m)).toList();
      controller.finishRefresh();
      setState(() {
        if (null != list) {
          _item.clear();
          childCount = list.length;
          _item.addAll(list);
        }
      });
    }, errorCallBack: (error) {
      controller.finishRefresh();
    });
  }

  ///数据回调监听
  void _onMsgEvent() {
    GlobalEvent().eventBus.on<ChatMsg>().listen((event) {
      print("收到eventBus数据：${event.toJson()}");
      _item.forEach((value) {
        ChatMsg itemMsg = value;
        if (event.fromId == itemMsg.fromId) {
          setState(() {
            itemMsg.message = event.message;
            itemMsg.msgTag = event.msgTag;
            itemMsg.unReadNum += 1;
          });
        }
      });
    });
  }
}
